<?php
namespace App\Repository\Db;

use App\Exceptions\ValidateException;
use App\Repository\Contracts\FeedbackInterface;
use App\Repository\Contracts\FeedbackJavaInterface;

/**
 * @Author:: HuangYin
 * @DateTime: 2017-01-16 13:23
 *
 * @Description:
 */
class FeedbackRepository extends Repository implements FeedbackInterface
{
    protected $rules = [
        'created' => [
            'store_id' => 'required',
            'content' => 'required|min:8'
        ],
        'updated' => [
            'store_id' => 'required',
            'content' => 'required|min:8'
        ]
    ];

    protected $messages = [
        'store_id.required'  => "门店 ID 不能为空",
        'content.required'  => "内容不能为空",
        'content.min'       => "内容长度最小4个字"
    ];

    protected function modelName()
    {
        return 'App\Model\Feedback';
    }

    public function created(array $data)
    {
        // 表单验证
        $this->validate($data, 'created');
        $result = $this->container->make(FeedbackJavaInterface::class)->syncCreated($data['store_id'], $data);
        if ($result['resultType'] === 'success') {
            $data['feedback_id'] = $result['resultData'];

            return $this->save($data);
        }

        throw new ValidateException('当前处于离线状态,请稍后');
    }

    public function detail($id)
    {
        return $this->find($id);
    }

    public function lists($limit, $page)
    {
        $query = $this->model;
        $total = $query->count();
        $list = $query->orderBy('id', 'desc')->simplePaginate($limit, ['*'], 'page', $page);

        return $this->simplePaginate('list', $list->items(), $total, ceil($total/$limit), $page);
    }

    public function findIdForFirst()
    {
        return $this->model->first(['feedback_id']);
    }
}